define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    require("chosen");

    var $attribute = $('[data-toggle="attribute"]');
    template.helper('specif_input_disabled', function(val) {
        return !val.length ? 'disabled="disabled"' : config.empty
    });
    template.helper('add_rule_input', function(type) {
        var rules="data-rule-required='true'";
        switch(type){
            case "ProductSn":
                rules="data-rule-required='true'";
            break;
            case "Price":
                rules='data-rule-ismoney="true" data-rule-required="true"';
            break;
            case "MarketPrice":
                rules='data-rule-ismoney="true" data-rule-required="true"';
            break;
            case "Store":
                rules='data-rule-digits="true" data-rule-required="true"';
            break;
            case "Weight":
                rules='data-rule-positive="true" data-rule-required="true"';
            break;
            case "Volume":
               rules='data-rule-positive="true" data-rule-required="true"';
            break;
        }
        return rules
    });
    template.helper('specif_class_disabled', function(val) {
        return !val.length ? 'style="color:#999;cursor:not-allowed;"' : config.empty
    });
    if (window.goods_data) {
        //赋值
        template.helper('attribute_selected', function(id, selected) {
            return window.goods_data.attributes[id] == selected ? 'checked="checked"' : config.empty
        });
        template.helper('attribute_checked', function(id, selected) {
            return window.goods_data.attributes[id] == selected ? 'class="active"' : config.empty
        });
        template.helper('attribute_disabled', function(id, checked) {
            if (window.goods_data.shelves) {
                return 'disabled="disabled"'
            } else {
                return config.empty;
            }

        });
        template.helper('specifications_checked', function(id, checked) {
            return $.inArray(checked, window.goods_data.specifications[id]) > -1 ? 'checked="checked"' : config.empty;
        });
    } else {
        template.helper('attribute_selected', function(id, selected) {
            return config.empty;
        });
        template.helper('specifications_checked', function(id, checked) {
            return config.empty;
        });
        template.helper('attribute_disabled', function(id, checked) {
            return config.empty;
        });

    }
    var attinit = function(customattr) {
        method.get(window.goods_setting.attribute_path, function(data) {
            data.shelves = window.goods_data.shelves;
            $attribute.html(template("attribute_template", data));
            $(".js_custom_list_contair dl").each(function() {
                var $this = $(this),
                    $ul = $this.find("ul:first"),
                    id = $ul.attr("id"),
                    text = $ul.find("li.active input[type='radio']:checked").data("title");
                $("#label_" + id).html(text);
            });
        }, config.lang.attributeError);
        customattr.customInput();
        $(document).on("click", ".js_custom_list_save", function() {
            var input = $(this).parents(".js_custom_list").find(".js_custom_input"),
                name = $(this).data("name"),
                tdata = customattr.customdata(input);
            if (customattr.customAttrValvali(input) && input.val()) {
                if (customattr.getAttrValExist(input.val(), tdata.attrid)) {
                    config.msg.info("已经存在的属性值");
                } else {
                    customattr.addAttrVal(tdata, name, input, false, $(this));
                }

            }
            if (!input.val()) {
                config.msg.error("属性值为空！");
            }
        });
        $(document).on("click", ".js_custom_list_cancel", function() {
            $(this).parents(".js_custom_list").next(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
        });
        $(document).on("click", ".js_custom_btn", function() {
            $(this).parents(".js_custom_list").prev(".js_custom_list").removeClass("hide");
            $(this).parents(".js_custom_list").addClass("hide");
            var $p = $(this).parents(".custom-select");
            $p.scrollTop($p.get(0).scrollHeight - 0 + 60);
        });
        $(document).on("click", ".js_custom_del", function() {
            var input = $(this).prev("a").find("input[type='radio']"),
                attrvalid = input.val();
            method.post(window.goods_setting.custom_attrvalue_del_path, function(data) {
                if (config.issucceed(data)) {
                    if (input.prop("checked")) {
                        $("#label_" + data.data.attrid).html("选择");
                    } else {
                        if (!customattr.getAttrValExist($("#label_" + data.data.attrid).text(), data.data.attrid)) {
                            $("#label_" + data.data.attrid).html("选择");
                        }
                    }
                    input.parents("li").remove();
                    config.msg.info(data.message || config.lang.removeSuccess);
                } else {
                    config.msg.error(data.message);
                }

            }, config.lang.attributeError, false, {
                "attrid": input.data("id"),
                "attrvalid": attrvalid
            });
        });

        $(document).on("click", ".js_add_attr_save", function() {
            var _this = $(this),
                $p = $(this).parents(".js_add_attr_form"),
                inputattr = $p.find(".js_add_attr_input"),
                inputattrv = $p.find(".js_add_attrv_input"),
                attrflag = customattr.customAttrValvali(inputattr),
                attrvflag = customattr.customAttrValvali(inputattrv);
            if (attrflag && attrvflag && inputattr.val() && inputattrv.val()) {
                var attrExit = customattr.getAttrExist(inputattr.val(), "custom-attr-dl-horizontal");
                if (attrExit.flag) {
                    if (customattr.getAttrValExist(inputattrv.val(), attrExit.id)) {
                        config.msg.info("已经存在的属性和属性值");
                    } else {
                        var name = $("#" + attrExit.id).find("input[type='radio']").attr("name");
                        customattr.addAttrVal({
                            "attrid": attrExit.id,
                            "attrval": inputattrv.val()
                        }, name, inputattrv, true, $(this));
                    }
                } else {
                    _this.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>提交中');
                    _this.button('loading');
                    $.ajax(window.goods_setting.custom_attr_path, {
                        type: "post",
                        data: {
                            "attrname": inputattr.val(),
                            "attrvalname": inputattrv.val()
                        },
                        dataType: "json"
                    }).done(function(d) {
                        _this.button('reset');
                        if (config.issucceed(d)) {
                            d.data.index = $(".js_custom_list_contair dl").length;
                            customattr.attrresult(d.data, inputattrv, "js_custom_list_contair");
                            config.msg.info(d.message);
                        } else {
                            config.msg.error(d.message);
                        }

                    }).fail(function() {
                        _this.button('reset');
                        config.msg.info(config.lang.attributeError);
                    });

                }
            } else {
                config.msg.error("请修改属性或属性值不正确的填写！");
            }

            if (!inputattr.val() && !inputattrv.val()) {
                config.msg.error("属性和属性值为空！");
            } else if (!inputattr.val()) {
                config.msg.error("属性为空！");
            } else if (!inputattrv.val()) {
                config.msg.error("属性值为空！");
            }
        });
        $(document).on("click", ".js_custom_attr_del", function() {
            var _this = $(this);
            config.msg.msgbox.confirm("确定删除整个分组吗？", function(result) {
                if (result) {
                    method.post(window.goods_setting.custom_attr_del_path, function(data) {
                        if (config.issucceed(data)) {
                            var $dl = $("#" + data.data.attrid).parents("dl"),
                                index = $dl.index(),
                                $nextdl = $dl.nextAll("dl");
                            $dl.remove();
                            $nextdl.each(function(i) {
                                $(this).find("input[type='hidden']").attr("name", "attribute[" + (index + i) + "].id");
                                $(this).find("input[type='radio']").attr("name", "attribute[" + (index + i) + "].selected");
                                $(this).find(".js_custom_list_save").attr("data-name", "attribute[" + (index + i) + "].selected");
                            });
                            config.msg.info(data.message || config.lang.removeSuccess);
                        } else {
                            config.msg.error(data.message);
                        }
                    }, config.lang.attributeError, false, {
                        "attrid": _this.data("id")
                    });

                }
            });
        });
        $(document).on("click", ".js_add_attr_btn", function() {
            $(".js_add_attr").addClass('hide');
            $(".js_add_attr_form").removeClass('hide');
        });
        $(document).on("click", ".js_add_attr_cancel", function() {
            customattr.closeAttrForm();
        });
        $(document).on("click", "dd li", function() {
            if ($(this).find("input[type='radio']").length > 0) {
                $(this).closest("li").show();
                $(this).closest("dd").find(".js_custom_dropdown_label").removeClass('error');
            }

        });
        $(document).on("click", ".js_custom_dropdown_label", function() {
            var id = $(this).data("id"),
                val = $(this).html();
            if (val == "选择") {
                $(this).html("");
                $("#" + id).find("li").show();
            } else {
                var num = 0;
                $("#" + id).find("input[type='radio']").each(function() {
                    if ($(this).prop("checked")) {
                        num = 1
                    }
                });
                if (num) {
                    $("#" + id).find("li").show();
                }
                //customattr.attrValSearch(val,id)
            }
            if ($("#" + id).css("display") == "block") {
                return false;
            }
        });
        $(document).on("click", ".dropdown-toggle", function() {
            $(this).find(".js_custom_dropdown_label").trigger('click');
        });
        $("body").on("blur", ".js_custom_dropdown_label", function() {
            var id = $(this).data("id"),
                val = $(this).html();
            if (!val) {
                $(this).html("选择");
                $("#" + id).find("input[type='radio']").each(function() {
                    $(this).removeAttr("checked");
                    $(this).parent().parent().show();
                    $(this).parent().parent().removeClass("active");
                });
                $(this).removeClass("error");
            } else if (val != "选择") {
                var num = 0;
                $("#" + id).find("input[type='radio']").each(function() {
                    if ($(this).prop("checked")) {
                        if ($(this).data("title") == val) {
                            num = 1
                        } else {
                            $(this).removeAttr("checked");
                            $(this).parent().parent().removeClass('active');
                        }

                    }
                });
                if (!num) {
                    $(this).addClass("error");
                } else {
                    $(this).removeClass("error");
                }
            }

        });
        $(document).on("keyup", ".js_custom_dropdown_label", function() {
            var id = $(this).data("id"),
                val = $(this).text(),
                $rli = $("#" + id).find(".js_search_result");
            var num = customattr.attrValSearch(val, id);
            if (!num) {
                $rli.find("a").html("未找到" + val);
                $rli.removeClass('hide');
            } else {
                $rli.addClass('hide');
            }
        })
    }
    var $specifications = $('[data-toggle="specifications"]');
    var $specificationstables = $("div.specificationstable");
    var $nospecifications = $("div.nospecifications");
    var Specifications = function() {
        this.specVals = null;
        this.firstLoad=true;
        this.speidarr=[];
        this.SpecificationsList = null;
        this.TableData = {
            ths: []
        };
        this.specificationstable = $('[data-toggle="specificationstable"]')
        var _self = this;
        var $specvals = $('[data-toggle="specvals"]')
        $('[data-toggle="specification-enable"]').on("click", function() {
            var enable = $(this).data("enable")
            $specifications.toggle(enable);
            if (enable) {
                $specificationstables.show();
                $nospecifications.hide();
                _self.acquire();
            } else {
                $specificationstables.hide();
                $nospecifications.show()
            }
        })
        var enable_specification = $('[data-toggle="specification-enable"]:checked').data("enable")
        if (enable_specification) {
            $specifications.show();
            $specificationstables.show();
            $nospecifications.hide();
        } else {
            $nospecifications.show();
        }

        method.get(window.goods_setting.specifications_path, function(d) {
            _self.SpecificationsList = d.data;
            $.each(d.data, function(index, item) {
                _self.TableData.ths.push(item)
            });
            $specifications.html(template("specifications_template", d))
            _self.init();
            enable_specification && _self.acquire()
        }, config.lang.specificationsError)

    };
    var Customattr = function() {

    }
    Customattr.prototype.getAttrExist = function(val, dl) {
        var arr = [],
            flag, isexist, id = "";
        $("." + dl).find("dt").each(function() {
            if ($(this).data("title")) {
                arr.push($(this).data("title"));
            }
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        id = $("." + dl).find("dt").eq(isexist).data("id");
        return {
            "flag": flag,
            "id": id
        };
    }
    Customattr.prototype.getAttrValExist = function(val, attrid) {
        var arr = [],
            flag, isexist;
        $("#" + attrid).find("input[type='radio']").each(function() {
            if ($(this).val()) {
                arr.push($(this).data("title"));
            }
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        return flag;
    }
    Customattr.prototype.attrValSearch = function(val, attrid) {
        var num = 0;
        $("#" + attrid).find("input[type='radio']").each(function() {
            var title = $(this).data("title") || "选择",
                $p = $(this).parent().parent();
            if (title) {
                title = title + "";
                if (title.indexOf(val) > -1) {
                    num++;
                    $p.show()
                } else {
                    $p.hide()
                }
            }
        });

        return num;
    }
    Customattr.prototype.getSpevalExist = function(val, attrid) {
        var arr = [],
            flag, isexist;
        $("#specvals_show_" + attrid).find(".js_specvals_show").each(function() {
            arr.push($(this).data("name"));
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        return flag;
    }
    Customattr.prototype.spevalExist = function(obj, attrid) {
        var arr = [],
            flag, isexist, valList = this.getSpelist(obj).arrval,
            result = "";
        $("#specvals_show_" + attrid).find(".js_specvals_show").each(function() {
            arr.push($(this).data("name"));
        });
        $(valList).each(function(index, item) {
            isexist = $.inArray(item, arr);
            if (isexist > -1) {
                result += item + ",";
            }
        });
        return result;
    }
    Customattr.prototype.getnSpevalExist = function(val) {
        var arr = [],
            flag, isexist;
        $(".js_spe_spev_show").find(".js_specvals_show").each(function() {
            arr.push($(this).data("name"));
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        return flag;
    }
    Customattr.prototype.addAttrVal = function(tdata, name, input, isattr, button) {
        var _this = this;
        button.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>提交中');
        button.button('loading');
        $.ajax(window.goods_setting.custom_attrvalue_path, {
            type: "post",
            data: tdata,
            dataType: "json"
        }).done(function(d) {
            button.button('reset');
            if (config.issucceed(d)) {
                d.data.checked = true, d.data.name = name;
                _this.result(d.data, input, isattr);
            } else {
                config.msg.error(d.message);
            }

        }).fail(function() {
            button.button('reset');
            config.msg.info(config.lang.attributeError)
        });
    }
    Customattr.prototype.closeAttrForm = function() {
        $(".js_add_attr").removeClass('hide');
        $(".js_add_attr_form").addClass('hide');
    }
    Customattr.prototype.attrresult = function(data, input, conclass) {
        var $target = $("." + conclass).find("dl:last");
        if($target.length){
            $(template("customattr_tem", data)).insertAfter($target);
        }else{
            $(template("customattr_tem", data)).insertBefore($("." + conclass).find(".line-dashed:first"));
        }
        
        input.val("");
        input.next(".js_limit").find("em").html(0);
        $(".js_add_attr_input").val("");
        $(".js_add_attr_input").next(".js_limit").find("em").html(0);
        this.closeAttrForm();
        config.msg.info(config.lang.saveSuccess);
    }
    Customattr.prototype.result = function(data, input, isattr) {
        var $target = $("#" + data.attrid).find(".js_custom_list:first");
        $("#" + data.attrid).find("li").removeClass("active");
        $("#" + data.attrid).find("li input[type='radio']").removeAttr("checked");
        $(template("customattrval_tem", data)).insertBefore($target);
        $("#label_" + data.attrid).html(data.title);
        $("#label_" + data.attrid).removeClass('error');
        $(document).trigger('click');
        input.val("");
        input.next(".js_limit").find("em").html(0);
        if (isattr) {
            $(".js_add_attr_input").val("");
            $(".js_add_attr_input").next(".js_limit").find("em").html(0);
            this.closeAttrForm();
        } else {
            $target.addClass('hide');
            $target.next(".js_custom_list").removeClass('hide');
        }
        $("#" + data.attrid).find(".js_search_result").addClass('hide');
        config.msg.info(config.lang.saveSuccess);
    }
    Customattr.prototype.customAttrValvali = function(input) {
        var flag = true,
            limit = input.data("limit") - 0,
            len = this.getInputLen(input);
        if (len > limit * 2) {
            flag = false;
        } else {
            flag = true;
        }
        return flag;

    }
    Customattr.prototype.customInput = function() {
        var _this = this;
        $(document).on("keyup", ".js_custom_input", function() {
            var len = _this.getInputLen($(this)),
                limit = $(this).data("limit") - 0,
                $limit = $(this).next(".js_limit");
            $limit.find("em").html(Math.ceil(len / 2));
            if (len > limit * 2) {
                $limit.addClass('error');
            } else {
                $limit.removeClass('error');
            }
        });
    }
    Customattr.prototype.getInputLen = function(input) {
        return input.val().replace(/[^\x00-\xff]/g, "xx").length;
    }
    Customattr.prototype.customdata = function(input) {

        return {
            "attrid": input.data("id"),
            "attrval": input.val()
        }
    }
    Customattr.prototype.getSpelist = function(obj) {
        var arr = [],
            idarr = [];
        obj.find(".js_specvals_temp").each(function() {
            arr.push($(this).data("name"));
        });
        obj.find(".js_specvals_del .js_del_specvals_val_list").each(function() {
            idarr.push($(this).data("id"));
        });
        return {
            "arrval": arr,
            "idarr": idarr
        };
    }
    Customattr.prototype.saveSpeval = function(data, button) {
        var _this = this;
        button.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>提交中');
        button.button('loading');
        $.ajax(window.goods_setting.custom_spevalue_path, {
            type: "post",
            data: data,
            dataType: "json"
        }).done(function(d) {
            button.button('reset');
            if (config.issucceed(d)) {
                _this.resultSpeval(d.data);
                config.msg.info(d.message || config.lang.removeSuccess);
            } else {
                config.msg.error(d.message);
            }

        }).fail(function() {
            button.button('reset');
            config.msg.info(config.lang.attributeError)
        });
    }
    Customattr.prototype.saveSpe = function(data, button) {
        var _this = this;
        button.data("loadingText", '<i class="fa fa-spinner fa-spin"></i>提交中');
        button.button('loading');
        $.ajax(window.goods_setting.custom_spe_path, {
            type: "post",
            data: data,
            dataType: "json"
        }).done(function(d) {
            button.button('reset');
            if (config.issucceed(d)) {
                _this.resultSpe(d.data);
                $(".js_nospe_tips").addClass("hide");
                config.msg.info(d.message || config.lang.removeSuccess);
            } else {
                config.msg.error(d.message);
            }
        }).fail(function() {
            button.button('reset');
            config.msg.info(config.lang.attributeError)
        });
    }
    Customattr.prototype.delSpeval = function(data, button) {
        var _this = this;
        $.ajax(window.goods_setting.custom_delspevalue_path, {
            type: "post",
            data: data,
            dataType: "json"
        }).done(function(d) {
            if (config.issucceed(d)) {
                _this.resultdelSpeval(d.data);
                Specif.SpecificationsListskey().delspvals(d.data.speid, d.data.spevalidList);
                config.msg.info(d.message || config.lang.removeSuccess);
            } else {
                config.msg.error(d.message);
            }
        }).fail(function() {
            config.msg.info(config.lang.attributeError)
        });
    }

    Customattr.prototype.resultSpeval = function(data) {
        var speid = data.speid,
            $target = $("#specvals_" + speid),
            $st = $("#specvals_show_" + speid).find("div");
        $target.append(template("specv_tem", data));
        this.closeopen(speid, true);
        $st.find(".js_specvals_temp").remove();
        $st.append(template("specv_result_tem", data));
    }
    Customattr.prototype.resultSpe = function(data) {
        $(template("spe_result_tem", data)).insertBefore($(".js_add_spe_div"));
        var item = {
            "id": data.id,
            "name": data.name,
            "all_val": data.spevalList
        };
        Specif.SpecificationsList.push(item);
        Specif.TableData.ths.push(item);
        Specif.acquire();
        $(".js_add_spe_input").val("");
        $(".js_add_spe_input").next(".js_limit").find("em").html(0);
        $(".js_spe_spev_show").find(".js_specvals_temp").remove();
        this.specloseopen(true);
    }
    Customattr.prototype.resultdelSpeval = function(data) {
        var speid = data.speid,
            $target = $("#specvals_" + speid),
            $st = $("#specvals_show_" + speid).find("div");
        this.closeopen(speid, true);
        $(data.spevalidList).each(function(index, item) {
            $target.find("#spe_" + item).remove();
        })
        $st.find(".js_specvals_del").remove();
    }
    Customattr.prototype.closeopen = function(id, flag) {
        $("#specvals_ed_" + id).toggleClass('hide', flag);
        $("#js_specifications_" + id).toggleClass('hide', !flag);
        $(".js_add_spe_div,.js_specifica_edit,.js_specifica_del").toggleClass('hide', !flag);
    }
    Customattr.prototype.specloseopen = function(flag) {
        $(".js_add_spe_form").toggleClass('hide', flag);
        $(".js_add_spe_div,.js_specifica_edit,.js_specifica_del").toggleClass('hide', !flag);
    }
    Customattr.prototype.getSpeExist = function(val) {
        var arr = [],
            flag, isexist, id = "";
        $("[data-toggle='specifications']").find(".js_specifica").each(function() {
            if ($(this).data("name")) {
                arr.push($(this).data("name"));
            }
        });
        isexist = $.inArray(val, arr);
        flag = isexist < 0 ? false : true;
        id = $("[data-toggle='specifications']").find(".js_specifica").eq(isexist).data("id");
        return {
            "flag": flag,
            "id": id
        };
    }

    Specifications.prototype.acquire = function() {

        this.selectSpecifications_vals = new Array();
        var _self = this;
        _self.TableData.ths = [];//选择一个规格 处理th
        $.each(this.SpecificationsList, function(index, item) {
            var speId = item.id;
            var selected_spevals = $("#specvals_" + speId).find('[type="checkbox"]:checked');
            var vals = new Array();
            $.each(selected_spevals, function(zindex, zitem) {
                vals.push({
                    val: zitem.title,
                    key: zitem.value
                })
            });
            var flag = vals.length > 0;
            flag && _self.TableData.ths.push(item); //选择一个规格 处理th
            flag && _self.selectSpecifications_vals.push(vals);
           
        });
        this.showtable = this.selectSpecifications_vals.length;
        //this.showtable = (this.selectSpecifications_vals.length == this.SpecificationsList.length);
       
        this.showtable&& this.generate(); //选择一个规格也可以生成
        if (!this.showtable) {
            this.specificationstable.html('<span class="help-block">请选择规格</span>');
        };
        
    }
    Specifications.prototype.generate = function() {
   
        this.res = this.combine(this.selectSpecifications_vals.reverse());
        this.rowspan();
        this.TableData.trs = [];
        var _self = this;
        if(_self.firstLoad){
            _self.getRes();
        }
        $.each(this.res, function(index, sps) {
            var tds = [];
            var tdkeys = [];
            $.each(sps, function(i, sp) {
                var td = [];
                td.rowspan = _self.row[i]>0? _self.row[i]:1;
                td.key = sp.key;
                td.val = sp.val;
                td.index = index;
                tds.push(td);
                tdkeys.push(sp.key);
            });
            var key = tdkeys.join(':');
            var rowitem = {
                tds: tds,
                index: index,
                key: key

            };
            _self.changeval(key);
            //赋值
            if (!window.goods_data) { //空的时候创建
                window.goods_data = {
                    products: {}
                }
            };
            if (window.goods_data && window.goods_data.products) {
                var rowdata = window.goods_data.products[key];
                if (rowdata) {
                    rowitem = $.extend({}, rowitem, rowdata);
                }
            }
            _self.TableData.trs.push(rowitem);

        }); 
        var thsname=[],thsids=[],thsnamearr=[];
        $.each(this.TableData.ths,function(index,item){
            thsname.push(item.name);
            thsnamearr.push(item.name);
            thsids.push(item.id);
        });
        this.TableData.thsname=thsname.join(",");
        this.TableData.thsids=thsids.join(",");
         this.TableData.thsnamearr=thsnamearr;
        this.specificationstable.html(template("specifications_table_template",this.TableData)); 
        $specificationstables.show()

    }
    Specifications.prototype.changeval = function(key) {
        !window.goods_data.products[key] && (window.goods_data.products[key] = {});
        /*$(document).on("change", '[data-id="' + key + '"]', function() {
            var $this = $(this),
                key = $this.data("id"),
                name = $this.data("name");
            var changrow = $('[data-id="' + key + '"]');
            var rowchang = {};
            $.each(changrow, function() {
                var f = {};
                var val = $this.val();
                f[name] = val;
                rowchang = $.extend({}, rowchang, f);

            });
            var itmes = $this.closest('tr').siblings().find('[data-name="' + name + '"]');
            if ($this.valid()) {
                $.each(itmes, function(index, val) {
                    var $zthis = $(this);
                    if ($zthis.val().length < 1) {
                        $zthis.val($this.val())
                        $zthis.valid();
                    };
                });
            }
            window.goods_data.products[key] = rowchang;
            // var keys = Object.keys(window.goods_data.products)
            // for (var i = keys.length - 1; i >= 0; i--) { 
            //     var itemKey=keys[i];
            //     var item=window.goods_data.products[itemKey]; 
            //     if (Object.keys(item).length==0) {
            //         item=rowchang;
            //     };
            // };
        })*/
    }
    Specifications.prototype.getRes = function() {
        var tempdata = jQuery.extend(true,{}, this.res),_self = this;
        this.res=[];
        $.each(tempdata, function(index, sps) {
            var tdkeys = [];
            $.each(sps, function(i, sp) {
                tdkeys.push(sp.key);
            });
            var getFlag=false;
            $(tdkeys).each(function(){
                var tdval=this;
                $(_self.speidarr).each(function(){
                    if(tdval==this){
                        getFlag=true;
                    }
                });
            });
            if(_self.speidarr.length&&getFlag){
                _self.res.push(sps);
            }else{
                var key = tdkeys.join(':');
                if (!window.goods_data) { //空的时候创建
                    window.goods_data = {
                        products: {}
                    }
                };
                if (window.goods_data && window.goods_data.products) {
                    var rowdata = window.goods_data.products[key];
                    if (rowdata) {
                        if(rowdata.Price!==undefined){
                            _self.res.push(sps);
                        }
                    }
                }
            }
            
        });
    }
    Specifications.prototype.rowspan = function() {
        var row = [], _self = this;
        if(_self.firstLoad){
            _self.getRes();
        }
        var rowspan = this.res.length;
        for (var n = this.selectSpecifications_vals.length - 1; n > -1; n--) {
            row[n] = parseInt(rowspan / this.selectSpecifications_vals[n].length);
            rowspan = row[n];
        }
        this.row = row.reverse();
    }
    Specifications.prototype.refresh = function() {
        var _self = this;
        _self.TableData.ths = [];
        var thsname=[],thsids=[],thsnamearr=[];
        $.each(_self.SpecificationsList, function(index, item) {
            _self.TableData.ths.push(item);
            thsname.push(item.name);
            thsnamearr.push(item.name);
            thsids.push(item.id);
        })
         this.TableData.thsnamearr=thsnamearr;
        this.TableData.thsname=thsname.join(",");
        this.TableData.thsids=thsids.join(",");
        this.acquire();
    }
    Specifications.prototype.SpecificationsListskey = function() {
        var _self = this;
        return {
            delsp: function(id) {
                var result = [];
                for (var i = 0, len = _self.SpecificationsList.length; i < len; i++) {
                    if (_self.SpecificationsList[i].id != id) {
                        result.push(_self.SpecificationsList[i]);
                    }
                };
                _self.SpecificationsList = result;
                _self.refresh();
            },
            delspvals: function(id, keys) {
                var tepm;
                for (var i = 0, len = _self.SpecificationsList.length; i < len; i++) {
                    if (_self.SpecificationsList[i].id == id) {
                        var result = []
                        for (var j = 0, jlen = _self.SpecificationsList[i].all_val.length; j < jlen; j++) {
                            for (var k = 0, klen = keys.length; k < klen; k++) {
                                if (_self.SpecificationsList[i].all_val[j].key != keys[k]) {
                                    result.push(_self.SpecificationsList[i].all_val[j]);
                                }
                            };
                        };
                        _self.SpecificationsList[i].all_val = result;
                    }
                };
                _self.refresh();
            }
        }


    }

    //合并规格
    Specifications.prototype.combine = function(arr) {
        var r = [];
        (function f(t, a, n) {
            if (n == 0) return r.push(t);
            for (var i = 0; i < a[n - 1].length; i++) {
                f(t.concat(a[n - 1][i]), a, n - 1);
            }
        })([], arr, arr.length);
        return r;

    };
    Specifications.prototype.init = function() {
        var _self = this;
        $(document).on('click', '[data-toggle="specvals"] input[type="checkbox"]', function() {
            _self.speidarr.push($(this).val());
            //_self.firstLoad=false;
            _self.acquire();
        });
        var customattr1 = new Customattr()
        $(document).on("click", ".js_add_speval", function() {
            var input = $(this).closest('.form-group').find("input"),
                id = $(this).data("id"),
                val = input.val();
            if (customattr1.customAttrValvali(input) && val) {
                if (customattr1.getSpevalExist(val, id)) {
                    $("#specvals_error_" + id).html('输入的规格值已存在');
                } else {
                    $("#specvals_error_" + id).html('');
                    $("#specvals_show_" + id).find("div").append(template("specv_show_tem", {
                        "val": val,
                        "speid": id
                    }));
                    input.val("");
                    input.next(".js_limit").find("em").html(0);
                }
            } else {
                $("#specvals_error_" + id).html('请输入规格值，长度不要超过15个字');
            }
        });
        $(document).on("click", ".js_spe_speval", function() {
            var input = $(".js_add_spev_input"),
                val = input.val();
            if (customattr1.customAttrValvali(input) && val) {
                if (customattr1.getnSpevalExist(val)) {
                    $(".js_js_spe_spev_error").html('输入的规格值已存在');
                } else {
                    $(".js_js_spe_spev_error").html('');
                    $(".js_spe_spev_show").append(template("specv_show_tem", {
                        "val": val,
                        "speid": ""
                    }));
                    input.val("");
                    input.next(".js_limit").find("em").html(0);
                }
            } else {
                $(".js_js_spe_spev_error").html('请输入规格值，长度不要超过15个字');
            }
        })
        $(document).on("click", ".js_specifica_edit", function() {
            var id = $(this).data("id");
            customattr1.closeopen(id, false);
            $(".js_add_spe_div,.js_specifica_edit,.js_specifica_del").addClass('hide');
        });
        $(document).on("click", ".js_specvals_val_save", function() {
            var id = $(this).data("id"),
                $dataobj = $(this).closest('.form-group').prev(".form-group"),
                opera = customattr1.getSpelist($dataobj),
                arr = opera.arrval,
                idarr = opera.idarr,
                data = {
                    "speid": id,
                    "speval": arr
                };
            if (arr.length > 0) {
                customattr1.saveSpeval(data, $(this));
            }
            if (idarr.length > 0) {
                customattr1.delSpeval({
                    "speid": id,
                    "idarr": idarr
                }, $(this));
            }
            if (arr.length < 1 && idarr.length < 1) {
                config.msg.error("请添加规格值或者删除规格值");
            }

        });
        $(document).on("click", ".js_specvals_val_cancel", function() {
            var id = $(this).data("id");
            customattr1.closeopen(id, true);
        });
        $(document).on("click", ".js_del_specvals_val_list", function() {
            var id = $(this).data("id");
            if (id) {
                $(this).parent().removeClass("js_specvals_result").addClass('hide js_specvals_del');
            } else {
                $(this).parent().remove();
            }

        });

        $(document).on("click", ".js_add_spe_btn", function() {
            customattr1.specloseopen(false);
        });
        $(document).on("click", ".js_add_spe_save", function() {
            var spe = $(".js_add_spe_input").val(),
                spev = $(".js_add_spev_input").val(),
                len = $(".js_spe_spev_show").find(".js_specvals_temp").length,
                speR = customattr1.getSpeExist(spe);
            $(".js_js_spe_spev_error").html("");
            if (spe) {
                if (customattr1.customAttrValvali($(".js_add_spe_input"))) {
                    if (speR.flag) {
                        if (len > 0) {
                            var spevR = customattr1.spevalExist($(".js_spe_spev_show"), speR.id);
                            if (spevR.length > 0) {
                                $(".js_js_spe_spev_error").html('输入的规格值：' + spevR + '已存在');
                            } else {
                                var id = speR.id,
                                    $dataobj = $(this).closest('.form-group').prev(".form-group"),
                                    opera = customattr1.getSpelist($dataobj),
                                    arr = opera.arrval,
                                    idarr = opera.idarr,
                                    data = {
                                        "speid": id,
                                        "speval": arr
                                    };
                                if (arr.length > 0) {
                                    customattr1.saveSpeval(data, $(this));
                                    $(".js_add_spe_input").val("");
                                    $(".js_add_spe_input").next(".js_limit").find("em").html(0);
                                    $(".js_spe_spev_show").find(".js_specvals_temp").remove();
                                    customattr1.specloseopen(true);
                                }
                            }
                        } else {
                            config.msg.error("请添加规格值");
                        }

                    } else {
                        var arrs = customattr1.getSpelist($(".js_spe_spev_show")).arrval,
                            data = {
                                "spe": spe,
                                "speval": arrs
                            };
                        if (arrs.length > 0) {
                            customattr1.saveSpe(data, $(this));
                        } else {
                            config.msg.error("请添加规格值");
                        }
                    }
                } else {
                    config.msg.error("规格只能输入5个字请修改规则");
                }
            } else {
                config.msg.error("请添加规格");
            }


        });
        $(document).on("click", ".js_add_spe_cancel", function() {
            customattr1.specloseopen(true);
        });
        $(document).on("click", ".js_specifica_del", function() {
            var id = $(this).data("id"),
                name = $(this).data("name");
            config.msg.msgbox.confirm("确定删除规格：" + name + "，及其所属的规格吗？", function(result) {
                if (result) {

                    method.post(window.goods_setting.custom_spe_del_path, function(data) {
                        if (config.issucceed(data)) {
                            config.msg.info(data.message || config.lang.removeSuccess);

                            $("#js_specifications_" + data.data.speid).remove();
                            $("#specvals_ed_" + data.data.speid).next(".line-dashed").remove();
                            $("#specvals_ed_" + data.data.speid).remove();
                            _self.SpecificationsListskey().delsp(data.data.speid);
                            if ($(".js_specifica").length < 1) {
                                $(".js_nospe_tips").removeClass("hide");
                            }


                        } else {
                            config.msg.error(data.message);
                        }

                    }, config.lang.attributeError, false, {
                        "speid": id
                    });
                }

            });
        });
    };
    //SpecificationsList
    $attribute.length > 0 && attinit(new Customattr());
    var Specif;
    if ($specifications.length > 0) {
        Specif = new Specifications(); //SpecificationsList
    };



    var $js_undertake = $(".js_undertake");
    if ($js_undertake.length > 0) {
        var $js_freight_container = $(".js_freight_container"),
            $js_freight_type = $(".js_freight_type"),
            $js_unify_container = $(".js_unify_container"),
            $js_template_container = $(".js_template_container"),
            $js_freight_template_loading = $(".js_freight_template_loading"),
            $js_freight_template = $(".js_freight_template"),
            $js_freight_template_refresh = $(".js_freight_template_refresh"),
            $js_freight_item = $(".js_freight_item");
        $js_undertake.on("click", function() {
            $js_freight_container.toggle($(this).hasClass('js_freight_container_show'))
        })
        $js_freight_type.on("click", function() {
            var $this = $(this);
            $js_unify_container.toggle($this.hasClass('js_unify_container_show'))
            $js_template_container.toggle($this.hasClass('js_template_container_show'))
        })
        $js_freight_item.on("click", function() {
            var $this = $(this);
            var dl = $this.closest('dl');
            $('input[type="text"]', dl).addAttr("disabled", !$this.prop("checked"))
        })
        $js_freight_template_refresh.on("click", function(e) {
            e && e.preventDefault();
            var $this = $(this),
                $remote = $this.data('remote') || $this.attr('href'),
                $icon = $this.find("i");
            $icon.addClass('fa-spin');
            var _tmp = ' <option value="{0}">{1}</option>'
            $js_freight_template.empty()
            $.post($remote).done(function(d) {
                if (d.data) {
                    $js_freight_template.append('<option value="">请选择</option>')
                    $.each(d.data, function(index, item) {
                        $js_freight_template.append(_tmp.format(item.id, item.name))
                    });
                };
                $icon.removeClass('fa-spin');
                $js_freight_template.focus();
            }).fail(function() {
                $icon.removeClass('fa-spin');
                config.msg.info(config.lang.exception)
            });

        });
        $(document).on("click", 'button[type="submit"]', function() {
            if ($js_unify_container.is(":visible")) {
                var item = $(".js_freight_item:checked");
                if (item.length < 1) {
                    config.msg.info("至少选择一个运送方式");
                    return false;
                };

            }
        })

    };
    //删除规格项方法
    $(document).on("click",'div[data-toggle="specificationstable"] .js_del_specvals_td',function(){
        var $this=$(this),key=$this.data("key"),val=$this.data("val"),$specif=$('div[data-toggle="specificationstable"]'),
        $list=$("tr[data-classes="+key+"]",$specif),listlen=$list.length,$spe=$('div[data-toggle="specifications"]');
        if(listlen>1){
            var $td=$("td:first",$list.eq(0)),keytd=$("td:first",$this.closest("tr")).data("key");
            if(keytd&&keytd==key){
                $list.eq(1).prepend("<td data-key="+keytd+" rowspan="+(listlen-1)+">"+val+"</td>");
            }else{
                $td.attr("rowspan",listlen-1);
            }
        }else{
            $("input[value="+key+"]",$spe).prop("checked",false);
        }
        var $table=$this.closest('table');
        $("td.sep_lists",$this.closest("tr")).each(function(){
            var $spetd=$(this),skey=$spetd.data("isid"),spelen=$("td.sep_lists[data-isid="+skey+"]",$table).length;
            if(spelen<2){
                $("input[value="+skey+"]",$spe).prop("checked",false);
            }
        });
        $this.closest('tr').remove();
        if($("tr",$specif).length<2){
            $("input[type=checkbox]",$spe).prop("checked",false);
            $('div[data-toggle="specificationstable"]').html('<span class="help-block">请选择规格</span>');
        }
    })
    //批量设置规格值
    $(document).on("click",'div[data-toggle="specificationstable"] .js_set_sepcif',function(){
        var $js_multy_set_sep=$(".js_multy_set_sep"),$this=$(this),thname=$this.data("thname"),
        thids=$this.data("thids")+"",spe=$this.data("speid")+"",ths=thname.split(","),thid=thids.split(","),list=[],
        speid=spe.split(":"),$div=$('div[data-toggle="specificationstable"]'),$tr=$this.closest('tr');
        $(ths).each(function(i){
            list.push({
                name:this,
                id:thid[i],
                speid:speid[i]
            });
        });
        $(".js_set_specif_list",$js_multy_set_sep).html(template("set_specif_list_template",{
            titles:[
                {
                    key:"ProductSn",
                    name:"商家编码",
                    val:$("input[data-name=ProductSn]",$tr).val()
                },
                {
                    key:"Price",
                    name:"销售价",
                    val:$("input[data-name=Price]",$tr).val()
                },
                {
                    key:"MarketPrice",
                    name:"市场价",
                    val:$("input[data-name=MarketPrice]",$tr).val()
                },{
                    key:"Store",
                    name:"库存",
                    val:$("input[data-name=Store]",$tr).val()
                },{
                    key:"Weight",
                    name:"重量",
                    val:$("input[data-name=Weight]",$tr).val()
                },{
                    key:"Volume",
                    name:"体积",
                    val:$("input[data-name=Volume]",$tr).val()
                }
            ],
            list:list
        }));
        $js_multy_set_sep.modal("show");
    });
    $(document).on("click",".js_multy_set_sep .js_set_sepcif_save",function(){
         var $input=$("input[type=checkbox]:checked",$(".js_set_specif_list")),$this=$(this),
            $div=$('div[data-toggle="specificationstable"]');
            $input.each(function(){
                var _this=$(this),key=_this.data("key"),id=_this.val(),
                $inputs=_this.closest('.form-group').prev("h5").find("input"),val=_this.data("val");
                $("td[data-isid="+id+"]",$div).each(function(){
                    $("input[data-name="+key+"]",$(this).closest("tr")).val(val);
                });
            });
            $this.closest(".js_multy_set_sep").modal("hide");
        
    });
    $(document).on("click",".js_multy_set_sep .js_set_specif_list input[type=radio]",function(){
        var $this=$(this),$input=$this.closest('.form-group').prev("h5").find("input");
        if($this.prop("checked")){
            $input.prop("disabled",false);
        }
    });
    $(document).on("click", '.js_save_submit', function() {
        if ($(".js_fileList li.imgbox").length < 1) {
            config.msg.error("至少选择一个商品图片");
            return false;
        } 
    });
    $(document).on("click", '.js_save_submit', function() {
        var $spe=$('[data-toggle="specifications"]'),
        len=$spe.find("input[type='checkbox']:checked").length;
        if (!$spe.is(":hidden")&&len < 1) {
            config.msg.error("至少选择一个商品规格");
            return false;
        } 
    });
    var $js_quota = $(".js_quota");
    $js_quota.on("click", function() {
        var flag = $(this).hasClass('js_quota_show');
        var $container = $(".js_quota_container");
        $container.toggleClass("hd", !flag).toggleClass("inline", flag)
    })
    $(document).on("click", ".js_submit", function() {
        $(this).closest('form').submit();
    })

    $(document).on("keypress", function(e) {
        var e = e || event;　
        var currKey = e.keyCode || e.which || e.charCode;
        if (13 == currKey) {
            if (!$(".js_spe_speval").closest('.js_enter_div').hasClass('hide')) {
                $(".js_spe_speval").trigger('click');
            }
            $(".js_add_speval").each(function() {
                if (!$(this).closest('.js_enter_div').hasClass('hide')) {
                    $(this).trigger('click');
                }
            });

            return false;
        }


    });
    $(document).on("click",".js_save_submit",function(){
        var $this=$(this),$confirm=$(this).data("confirm"),confirmMsg=$this.data("confirmMsg");
        if($confirm){
            var storway=$("#js_store_way"),checked=$(".js_way_select:checked").val();
            if(checked==0&&storway.val()!=checked){
                config.msg.msgbox.confirm({
                    message: confirmMsg || config.lang.confirmPost,
                    buttons: {
                        confirm: {
                            label: $this.data('confirmText') || "确定修改"
                        }
                    },
                    callback: function(result) {
                        if (result) {
                            $this.submit();
                        }
                    }
                });
                return false;
            }
            
        }
        
    });
    $(document).on("click",".js_search_add_submit",function(){
        var $form=$(this).closest("form"),action=$form.attr("action"),
        data=$(".talbe-search").serialize();
        $form.attr("action",action.format(data));
    });
    $(document).on("click",".js_edit_search",function(){
        var $this=$(this),href=$this.attr("href"),
        data=$(".talbe-search").serialize();
        $this.attr("href",href.format(data));
    });

})
